import Vue from 'vue'
import Vuex from 'vuex'
// 导入axios,axios是异步请求
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  data () {
    return {

    }
  },

  state: {
    // 所有的任务列表
    list: [],
    // 文本框的内容
    inputValue: 'aaa',
    // 下一个id
    nextId: 5,
    viewKey: 'all'
  },
  mutations: {
    initList (state, data) {
      state.list = data
    },
    // 为state中的inputValue赋值
    setInputValue (state, val) {
      state.inputValue = val
    },
    // 添加列表项
    addItem (state) {
      const obj = {
        id: state.nextId++,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.inputValue = ''
    },
    removeItem (state, id) {
      state.list = state.list.filter(item =>
        // 配置文件修改了需要重新run,不然无法启动
        item.id != id
      )
    },
    changeStatus (state, param) {
      const index = state.list.findIndex(item => item.id == param.id)
      if (index != -1) {
        state.list[index].done = param.status
      }
    },
    cleanDone (state) {
      state.list = state.list.filter(item => item.done == false)
    },
    // 修改视图的关键字
    changeViewKey (state, key) {
      state.viewKey = key
    }
  },
  actions: {
    getList (context) {
      axios.get('/list.json').then(({ data }) => {
        console.log(data)
        context.commit('initList', data)
      })
    }
  },
  getters: {
    // 统计未完成的任务的条数
    unDoneLength (state) {
      let unDone = 0
      unDone = state.list.reduce((amt, item) => {
        if (item.done == false) {
          amt = amt + 1
          return amt
        } else {
          return amt
        }
      }, 0)
      return unDone
    },
    viewList (state) {
      if (state.viewKey == 'all') return state.list
      if (state.viewKey == 'undone') {
        return state.list.filter(item => item.done === false)
      }
      if (state.viewKey == 'done') {
        return state.list.filter(item => item.done === true)
      }
    }
  },
  modules: {
  }
})
